package cn.gailvlun.gll.presentation.xroom.adapter

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.annotation.ColorInt
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.PlaceHolder
import cn.gailvlun.gll.bean.SelectHolder
import cn.gailvlun.gll.databinding.ItemGameEndBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.ListRes
import cn.gailvlun.gll.net.cross.CrossCommentReq
import cn.gailvlun.gll.net.cross.GetTagRes
import cn.gailvlun.gll.presentation.base.App
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.util.ToastUtil
import com.blankj.utilcode.util.ConvertUtils
import com.github.markzhai.recyclerview.BaseViewAdapter
import com.google.android.flexbox.FlexboxItemDecoration
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.dialog_game_end.*

class GameEndDialog(context: Context, private val gameEndTime: Int, private val isFirst: Boolean,
                    private val matchId: Int) : BaseDialog(context) {

    private var mAdapter: GameEndAdapter? = null
    private var mLayoutManager: GridLayoutManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.dialog_game_end)

        rv.addItemDecoration(GridItemDecoration(ConvertUtils.dp2px(10f), 2))

        mAdapter = GameEndAdapter(context)
        mAdapter?.setDecorator { holder, _, _ ->
            (holder.binding as ItemGameEndBinding).tvGameEndTag.setOnClickListener {
                mAdapter?.click(holder.adapterPosition)
                tv_ensure.isEnabled = true
            }
        }
        rv.adapter = mAdapter

        mLayoutManager = GridLayoutManager(context, 2)
        rv.layoutManager = mLayoutManager

        tv_shuffle.setOnClickListener {
            shuffleTag()
        }

        tv_ensure.setOnClickListener {
            ensure()
        }

        shuffleTag()

        cdv.toggle()
        RxUtil.countDown(gameEndTime.toLong())
                .subscribe(object : Observer<Long> {
                    override fun onComplete() {
                        secureDismiss()
                    }

                    override fun onSubscribe(d: Disposable) {
                        countDown = d
                    }

                    override fun onNext(t: Long) {
                        cdv.setText(t.toInt())
                    }

                    override fun onError(e: Throwable) {

                    }
                })

        setCancelable(false)
    }

    private var countDown: Disposable? = null

    override fun secureDismiss() {
        super.secureDismiss()

        countDown?.dispose()
    }

    private fun shuffleTag() {
        val dialog = DialogUtil.showIndeterminate(context)
        HttpMethods.getCrossService()
                .tag
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<ListRes<GetTagRes>>() {
                    override fun onSuccess(response: ListRes<GetTagRes>) {
                        mAdapter?.set(SelectHolder.transform(response.results.subList(0, 4)))
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<GetTagRes>?, code: Int) {
                        DialogUtil.showError(context, errMsg)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        dialog.dismiss()
                    }
                })
    }

    private fun ensure() {
        val dialog = DialogUtil.showIndeterminate(context)
        val crossCommentReq = CrossCommentReq()
        crossCommentReq.tag = mAdapter?.getSelectTag()?.content
        crossCommentReq.x_match_result_id = matchId
        crossCommentReq.isIs_first = isFirst
        HttpMethods.getCrossService()
                .comment(crossCommentReq)
                .compose(RxUtil.applyScheduler())
                .subscribe(object : HttpSubscriber<PlaceHolder>() {
                    override fun onSuccess(response: PlaceHolder?) {
                        rv.visibility = View.GONE
                        tv_shuffle.visibility = View.GONE
                        tv_ensure.visibility = View.GONE
                        iv_done.visibility = View.VISIBLE
                        tv_done.visibility = View.VISIBLE

                        ToastUtil.showCenter("收到！\n对方还在选择，稍等哦～")
                    }

                    override fun onFailure(errMsg: String?, response: PlaceHolder?, code: Int) {

                    }

                    override fun onFinish() {
                        super.onFinish()

                        dialog.dismiss()
                    }
                })
    }

    object Util {
        @JvmStatic
        fun getBackground(item: SelectHolder<GetTagRes>): Drawable {
            return if (item.selected) {
                App.getInstance().resources.getDrawable(R.drawable.six_radius_apricot)
            } else {
                App.getInstance().resources.getDrawable(R.drawable.six_radius_pale_grey_three)
            }
        }

        @JvmStatic
        @ColorInt
        fun getTextColor(item: SelectHolder<GetTagRes>): Int {
            return if (item.selected) {
                App.getInstance().resources.getColor(R.color.white)
            } else {
                App.getInstance().resources.getColor(R.color.warmGrey)
            }
        }
    }
}